package cn.tedu.lucky.draw.server.job.config;

import cn.tedu.lucky.draw.server.job.processor.ActivityProcessor;
import cn.tedu.lucky.draw.server.protrocol.po.Activity;
import cn.tedu.lucky.draw.server.repository.ActivityRepository;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.data.RepositoryItemReader;
import org.springframework.batch.item.data.RepositoryItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ActivityConfig {
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private ActivityRepository activityRepository;

    @Bean
    public ItemReader<Activity> activityReader() {
        RepositoryItemReader<Activity> reader = new RepositoryItemReader<>();
        reader.setRepository(activityRepository);
        reader.setMethodName("findByStatusAndEndTimeBefore");
        Map<String, Sort.Direction> sorts = new HashMap<>();
        sorts.put("id", Sort.Direction.ASC); // 假设使用id字段进行排序
        reader.setSort(sorts);
        reader.setArguments(Arrays.asList(1, LocalDateTime.now()));
        return reader;
    }

    @Bean
    public ActivityProcessor activityProcessor() {
        return new ActivityProcessor();
    }

    @Bean
    public ItemWriter<Activity> activityWriter() {
        RepositoryItemWriter<Activity> activityRepositoryItemWriter = new RepositoryItemWriter<>();
        activityRepositoryItemWriter.setRepository(activityRepository);
        activityRepositoryItemWriter.setMethodName("save");
        return activityRepositoryItemWriter;
    }

    @Bean
    public Step activitiesExpirationStep() {
        return stepBuilderFactory.get("activitiesExpirationStep")
                .<Activity, Activity> chunk(100) // 每次处理100条记录
                .reader(activityReader())
                .processor(activityProcessor())
                .writer(activityWriter())
                .build();
    }
    @Bean
    public Job activityJob() {
        return jobBuilderFactory.get("activityJob")
                .start(activitiesExpirationStep())
                .incrementer(new RunIdIncrementer())
                .build();
    }
}
